//
//  PhotoBrowserViewController.swift
//  weibo
//
//  Created by 张衡 on 15/8/16.
//  Copyright © 2015年 张衡. All rights reserved.
//



import UIKit
import SVProgressHUD

private let ZHPhotoBrowserViewCell = "ZHPhotoBrowserViewCell"

class PhotoBrowserViewController: UIViewController {
    
    // MARK: 属性
    // URL 的数组
    var urls: [NSURL]
    
    // 选中照片的索引
    var selectedIndex: Int
    
    init(urls: [NSURL], Index: Int) {
        
        // 给自己属性设置数值
        self.urls  = urls
        selectedIndex = Index
        
        // 调用父类的构造函数
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // print(urls)
    }
    
    
    // 提示： 所有成熟的第三方框架，只有sdwebimage支持gif播放，但内存消耗大
    // 如果使用自动布局，在拖动cell 的时候，会被重新调用，造成照片错位
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        // 造成退出会闪bug
//        var screenBounds = UIScreen.mainScreen().bounds
//        screenBounds.size.width += 20
//        
//        view.frame = screenBounds
//        if selectedIndex == 0 {
//            return
//        }
        // 跳转到用户选中的图片 (解决点击图片首先出现第一张的bug)
        let indexPath = NSIndexPath(forItem: selectedIndex, inSection: 0)
        
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        // print(indexPath)
    }
    // 方法要选好
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
//        会跳跃，造成闪
//        // 跳转到用户选中的图片 (解决点击图片首先出现第一张的bug)
//        let indexPath = NSIndexPath(forItem: selectedIndex, inSection: 0)
//        
//        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    
    override func loadView() {
        // 提前给view 尺寸
        
        var screenBounds = UIScreen.mainScreen().bounds
        screenBounds.size.width += 20
        view = UIView(frame: screenBounds)
        
        // view.backgroundColor = UIColor(colorLiteralRed: 246 / 256.0, green: 246 / 256.0, blue: 246 / 256.0, alpha: 0.9)
        
        setupUI()
    }
    
    
    private func setupUI() {
        // 1. 添加控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        // 设置控件位置 (三者约束设置要统一，使用同一种方式）
        collectionView.frame = view.bounds
        // collectionView.backgroundColor = UIColor.clearColor()
        let rect = CGRect(x: 0, y: UIScreen.mainScreen().bounds.height - 40, width: 100, height: 32)
        closeButton.frame = CGRectOffset(rect, 8, 0)
        saveButton.frame = CGRectOffset(rect, UIScreen.mainScreen().bounds.width - rect.width - 8, 0)
        
//        // 2. 自动布局 
//        collectionView.translatesAutoresizingMaskIntoConstraints = false
//        closeButton.translatesAutoresizingMaskIntoConstraints = false
//        saveButton.translatesAutoresizingMaskIntoConstraints = false
//        
//        let dict = ["cv": collectionView, "save": saveButton, "close": closeButton]
//        
//        // . collection全屏
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        
//        
//        // .. 两个按钮
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[save(32)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[close(32)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        
//        // 提示：约束关系： = , >= , <=
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[close(100)]-(>=0)-[save(100)]-28-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        // 3. 监听方法
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        
        prepareCollectionView()
    }
    
    // 按钮的点击事件，是通过消息循环传导了，用private 要加上@objc
    @objc private func save() {
        print("save")
        // 1. 获取照片 // 此方法，获得当前屏幕上显示cell 
        let indexPath = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoBrowserCell
        
        // 要判断图像视图中是否存在图像，因为 sdwebimage 不一定能够下载到图片
        guard let image = cell.imageView.image  else{
            return
        }
        // 2. 保存
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        
    }
    
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
        
        print(error)
        print(image)
        let msg = (error == nil) ? "保存成功" : "保存失败"
        
        SVProgressHUD.showInfoWithStatus(msg)
        
        
    }
    
    @objc private func close() {
        print("close")
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 准备collectionview 
    func prepareCollectionView() {
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: ZHPhotoBrowserViewCell)
        collectionView.dataSource = self
        // collectionView.backgroundColor = UIColor.blueColor()
        
        // 设置布局
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        // itemsize 会跟随宽20
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView.pagingEnabled = true
        
        
    }
    
    
    // MARK: - 懒加载
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 14, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    
    // view视图 中的 scrollview 的 缩放比例
    private var photoScale: CGFloat = 1

}



extension PhotoBrowserViewController: UICollectionViewDataSource, PhotoBrowserCellDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ZHPhotoBrowserViewCell, forIndexPath: indexPath) as! PhotoBrowserCell
        
        
        cell.imageURL = urls[indexPath.item]
        // print(indexPath.item)
        // cell.imageURL = urls[selectedIndex]
        
        // cell.backgroundColor = UIColor.blackColor()
        
        cell.photoDelegate = self
        
        return cell
    }
    
    // MARK: - PhotoBrowserCellDelegate 实现代理方法
    // 缩放进行中
    func photoBrowserCellZoom(scale: CGFloat) {
        // 交互式转场
        // print(scale)
        
        // 记录缩放比例
        photoScale = scale
        
        // 设置控件的隐藏
        hiddenControls(scale < 1)
        
        // 开始转场
        if scale < 1.0 {
            startInteractiveTransition(self)  // 改变view的transform 和 alph
//          startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning)
            // startInteractiveTransition 这个 函数的调用 要求控制器遵守 UIViewControllerInteractiveTransitioning 协议
            // startInteractiveTransition 这个 函数的参数 要求控制器遵守 UIViewControllerContextTransitioning 协议
            
        }
        else {
            view.transform = CGAffineTransformIdentity
            view.alpha = 1
        }
    }
    
    /// 缩放完成
    func photoBrowserCellEndZoom() {
        // 判断缩放比例
        if photoScale < 0.8 {
            // 结束转场
            completeTransition(true)
            
        } else {
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.view.transform = CGAffineTransformIdentity
                self.view.alpha = 1
                }, completion: { (_) -> Void in
                    self.photoScale = 1
                    self.hiddenControls(false)
            })
        }
    }
    
    /// 当前显示的图像视图
    func currentImageView() -> UIImageView {
        let cell = collectionView.cellForItemAtIndexPath(currentImageIndex()) as! PhotoBrowserCell
        return cell.imageView
    }
    
    /// 当前显示的照片索引
    func currentImageIndex() -> NSIndexPath {
        return collectionView.indexPathsForVisibleItems().last!
    }
    
    /// 隐藏控件
    private func hiddenControls(hidden: Bool) {
        collectionView.backgroundColor = hidden ? UIColor.clearColor() : UIColor.blackColor()
        
        closeButton.hidden = hidden
        saveButton.hidden = hidden
    }
}


extension PhotoBrowserViewController: UIViewControllerInteractiveTransitioning {// 遵守协议
    
    // 开始交互转场
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        // 设置变形
        view.transform = CGAffineTransformMakeScale(photoScale, photoScale)
        // 设置透明度
        view.alpha = photoScale
    }
}

// Context 提供转场所有细节
extension PhotoBrowserViewController: UIViewControllerContextTransitioning { // 遵守协议
    
    /// 结束转场动画
    func completeTransition(didComplete: Bool) {
        // 关闭当前控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 容器视图
    func containerView() -> UIView? {
        return view.superview
    }
    
    func isAnimated() -> Bool { return true }
    func isInteractive() -> Bool { return true }
    func transitionWasCancelled() -> Bool { return false }
    func presentationStyle() -> UIModalPresentationStyle { return UIModalPresentationStyle.Custom }
    
    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition() {}
    func cancelInteractiveTransition() {}
    
    func viewControllerForKey(key: String) -> UIViewController? { return self }
    func viewForKey(key: String) -> UIView? { return view }
    func targetTransform() -> CGAffineTransform { return CGAffineTransformIdentity }
    func initialFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
    func finalFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
}






